#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>

#define FIFO "/tmp/myfifo"

int main()
{
    pid_t pid;
    int pfd, cfd;
    char buff[128];
    const char hello[] = "hello from child";
    if (mkfifo(FIFO, 0666) != 0) {
        perror("mkfifo failed");
        return -1;
    }
    /* FIFO(named pipe) is also half-duplex. */
    pfd = open(FIFO, O_RDONLY | O_NONBLOCK);
    cfd = open(FIFO, O_WRONLY);
    if ((pid = fork()) < 0) {
        perror("fork failed");
        return -1;
    } else if (pid == 0) { /* child */
        close(pfd);
        write(cfd, hello, sizeof(hello));
        close(cfd);
    } else { /* parent */
        close(cfd);
        sleep(1); /* wait for write */
        memset(buff, 0, sizeof(buff));
        read(pfd, buff, sizeof(buff));
        printf("parent read: %s\n", buff);
        fflush(stdout);
        waitpid(pid, NULL, 0);
        unlink(FIFO);
    }
    return 0;
}
